package com.aliyun.oss.config;

import com.aliyun.oss.interceptor.TokenInterceptor;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5173")
                // 使用 allowedOriginPatterns 代替 allowedOrigins
                .allowedOriginPatterns("*")
                // 允许凭证，如果你的前端请求需要携带cookie或认证头，此项必须为true
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH") // 明确列出方法，确保包含OPTIONS
                .allowedHeaders("*") // 允许所有头，或根据需要明确指定，如"Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"
                .maxAge(3600); // 预检请求的缓存时间（秒），可减少预检请求次数

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //        作用：添加拦截器
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login")
                .excludePathPatterns("OPTIONS")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/user/shop/status");

//                .excludePathPatterns("/**", "OPTIONS");
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
